//
//  WebServiceHelper.m
//  FPTest
//
//  Created by zhaohong on 2017/11/23.
//  Copyright © 2017年 zhaohong. All rights reserved.
//

#import "WebServiceHelper.h"
#define CustomErrorDomain @"com.WebServiceHelper"
typedef enum
{
    
    PARAMETER_ERROR = 0,//参数错误
    EXCEPTION_DESCRIPTION, //网络错误
    INTERFACE_CHECKFAIL,//接口验证失败
    BC_CODEFAIL//渠道码不存在
    
}CustomErrorFailed;// 用于表示错误类型


@implementation WebServiceHelper
#pragma mark 请求最基本数据
+(void)postWithURLString:(NSString *)url
              parameters:(NSDictionary *)parameters
                 success:(void (^)(id))success
                 failure:(void (^)(NSError *))failure
{
    
    NSString *postUrl = [NSString stringWithFormat:@"%@/%@",kHTTPREQUEST_BASE_URL,url];
    
    //需要提交的参数（原参数加加密验证的数据）
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    manager.requestSerializer.timeoutInterval = 30;
    
    //因为这个测试的地址需要用GET方法获取，所以这里我先用GET的方法调用了
    [manager GET:postUrl parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         if (success)
         {
             success(responseObject);
             
         }
         
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         if (failure) {
             
             failure(error);
         }
     }];
    
}



#pragma mark ------------------------------请求model数据--------------------------
#pragma mark 请求model数据
+ (void)postAndGetJsonModelWithURLString:(NSString *)url
                              parameters:(NSDictionary *)parameters
                              modelClass:(Class)modelClass
                                 success:(void (^)(BaseModel *baseModel))success
                                 failure:(void (^)(NSError *error))failure
{
    // 检查需要返回的model类型是否存在
    if (modelClass == nil)
    {
        if (failure != nil)
        {
            NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"is a parameter error"                                                                      forKey:NSLocalizedDescriptionKey];
            NSError *aError = [NSError errorWithDomain:CustomErrorDomain code:PARAMETER_ERROR userInfo:userInfo];
            failure(aError);
            NSLog(@"\n\nmodelClass参数 == nil\n\n");
        }
        return ;
    }
    
    
    [WebServiceHelper postWithURLString:url parameters:parameters success:^(id responseObject) {
        // 检查data
        if (![responseObject isKindOfClass:[NSDictionary class]])
        {
            NSLog(@"\n\njsonModelRequestWithInfo请求的数据不是字典类型: data is invalid\n\n");
            NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"数据不是字典类型"                                                                      forKey:NSLocalizedDescriptionKey];
            NSError *aError = [NSError errorWithDomain:CustomErrorDomain code:PARAMETER_ERROR userInfo:userInfo];
            failure(aError);
            
        }
        else
        {
            // 正常返回
            BaseModel *baseModel = [[modelClass alloc] initWithDataDic:responseObject];
            if (success != nil)
            {
                success(baseModel);
            }
        }
        
    } failure:^(NSError *error) {
        failure(error);
    }];
    
    
}


#pragma mark ------------------------------请求有对象所有选的model数据--------------------------
#pragma mark 请求有对象所有选的model数据
+ (void)postAndGetJsonModelWithURLString:(NSString *)url
                              parameters:(NSDictionary *)parameters
                              modelClass:(Class)modelClass
                               requester:(id)requester
                                     key:(NSString *)key
                                 success:(void (^)(BaseModel *baseModel))success
                                 failure:(void (^)(NSError *error))failure
{
    // 检查实参
    if (requester == nil || key == nil)
    {
        if (failure != nil)
        {
            NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"请求的参数requester == nil, or key ==nil"                                                                      forKey:NSLocalizedDescriptionKey];
            NSError *aError = [NSError errorWithDomain:CustomErrorDomain code:PARAMETER_ERROR userInfo:userInfo];
            failure(aError);
            
        }
        return ;
    }
    
    
    [WebServiceHelper postAndGetJsonModelWithURLString:url parameters:parameters modelClass:modelClass success:^(BaseModel *baseModel) {
        //kvo设置属性值
        [requester setValue:baseModel forKey:key];
        if (success != nil) {
            success(baseModel);
        }
    } failure:^(NSError *error) {
        if (error != nil) {
            
            //            //如果网络请求失败，则调用一下pageNum的值减1，防止pullUp失败时也会让pageNum加1
            //            if ([requester isKindOfClass:[BaseViewController class]]) {
            //                [requester reducePageNum];
            //            }
            failure(error);
        }
    }];
}

@end

